package com.mt.mall.service.merchant.impl;

import com.mt.mall.dao.merchant.FollowStoreDao;

import com.mt.common.core.exception.BusinessException;
import com.mt.common.core.web.base.PageDTO;
import com.mt.common.core.web.base.PageResultDTO;
import com.mt.common.core.web.base.BaseEntity;
import com.mt.common.core.web.BaseService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.mt.mall.entity.merchant.FollowStore;
import com.mt.mall.service.merchant.FollowStoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
@Transactional
public class FollowStoreServiceBean extends BaseService implements FollowStoreService {

    private static Logger logger = LogManager.getLogger();

	@Autowired
	private FollowStoreDao followStoreDao;

	@Resource
	private RedisTemplate<String, List<FollowStore>> redisTemplate;

	@Autowired
	StringRedisTemplate stringRedisTemplate;

	/**
	 * 根据分页参数查询关注店铺集合
	 *
	 * @param pageDTO 分页条件
	 */
	@Override
	public PageResultDTO findFollowStores(PageDTO pageDTO){
        pageDTO.setStartIndex((pageDTO.getCurrentPage()-1)*pageDTO.getPageSize());
		//TODO:请在此校验参数的合法性
		this.validateFindFollowStores(pageDTO);
		List<FollowStore> followStoreDTOS = this.followStoreDao.findFollowStores(pageDTO);
		Long totalCount = this.followStoreDao.findFollowStoreTotalCount(pageDTO);

		PageResultDTO pageResultDTO = new PageResultDTO();
		pageResultDTO.setTotalCount(totalCount);
		pageResultDTO.setDatas(followStoreDTOS);

		return pageResultDTO;
	}

	/**
	 * 查询全部关注店铺集合
	 *
	 */
	@Override
	public List<FollowStore> findAllFollowStores(){
		return this.followStoreDao.findAllFollowStores();
	}

	/**
	 * 查询所有关注店铺集合(只提取ID 和 Name)
	 *
	 */
	@Override
	public List<FollowStore> findAllFollowStoresWithIdName(){
		//TODO:请在此校验参数的合法性
		this.validateFindAllFollowStoresWithIdName();
		return this.followStoreDao.findAllFollowStoresWithIdName();
	}

	/**
	 * 根据名称查询关注店铺集合(只提取ID 和 Name)
	 *
	 * @param followStoreName 名称
	 */
	@Override
	public List<FollowStore> findFollowStoresWithIdNameByName(String followStoreName){
		//TODO:请在此校验参数的合法性
		this.validateFindFollowStoresWithIdNameByName(followStoreName);
		//TODO:缓存取对应参数
		Set<String> keys = stringRedisTemplate.keys("searchData:FollowStore_where_followStoreName_" + followStoreName);
		List<FollowStore> followStores = new ArrayList<>();
		if (keys.isEmpty()) {
		followStores = this.followStoreDao.findFollowStoresWithIdNameByName(followStoreName);
		redisTemplate.opsForValue().set("searchData:FollowStore_where_followStoreName_" + followStoreName, followStores, 30, TimeUnit.DAYS);
		} else {
		followStores = redisTemplate.opsForValue().get("searchData:FollowStore_where_followStoreName_" + followStoreName);
		}
		return followStores;
	}

	/**
	 * 根据ID查询指定的关注店铺(只提取ID 和 Name)
	 *
	 * @param followStoreId Id
	 */
	@Override
	public FollowStore findFollowStoresWithIdNameById(Long followStoreId){
		//TODO:请在此校验参数的合法性
		this.validateFindFollowStoresWithIdNameById(followStoreId);
		return this.followStoreDao.findFollowStoresWithIdNameById(followStoreId);
	}

	/**
	 * 根据ID查询指定的关注店铺
	 *
	 * @param followStoreId Id
	 */
	@Override
	public FollowStore findFollowStore(Long followStoreId){
		//TODO:请在此校验参数的合法性
		this.validateFindFollowStore(followStoreId);
		return this.followStoreDao.findFollowStore(followStoreId);
	}

	/**
	 * 根据ID查询指定的关注店铺(包含外键)
	 *
	 * @param followStoreId Id
	 */
	@Override
	public FollowStore findFollowStoreWithForeignName(Long followStoreId){
		//TODO:请在此校验参数的合法性
		this.validateFindFollowStoreWithForeignName(followStoreId);
		return this.followStoreDao.findFollowStoreWithForeignName(followStoreId);
	}

	/**
	 * 新增关注店铺
	 *
	 * @param followStore 实体对象
	 */
	@Override
	public FollowStore saveFollowStore(FollowStore followStore){
		//TODO:请在此校验参数的合法性
		this.validateSaveFollowStore(followStore);
		//TODO:填充公共参数
		this.setSavePulicColumns(followStore);
		Long rows = this.followStoreDao.saveFollowStore(followStore);
		if(rows != 1)
		{
			String error = "新增保存关注店铺出错，数据库应该返回1,但返回了 "+rows;
			throw new BusinessException(error);
		}
		return followStore;
	}

	/**
	 * 更新关注店铺
	 *
	 * @param followStore 实体对象
	 */
	@Override
	public FollowStore updateFollowStore(FollowStore followStore){
		//TODO:请在此校验参数的合法性
		this.validateUpdateFollowStore(followStore);
		Long rows = this.followStoreDao.updateFollowStore(followStore);
		if(rows != 1)
		{
			String error = "修改保存关注店铺出错，数据库应该返回1,但返回了 "+rows+",数据可能被删除";
			throw new BusinessException(error);
		}
		return followStore;
	}

	/**
	 * 根据ID删除关注店铺
	 *
	 * @param followStoreId ID
	 */
	@Override
	public void deleteFollowStore(Long followStoreId){
		//TODO:请在此校验参数的合法性
		this.validateDeleteFollowStore(followStoreId);

		Map<Class<? extends BaseEntity>,EntityUsage> entityUsageMap = this.checkForeignEntity(FollowStore.class, followStoreId);
		if(entityUsageMap != null && entityUsageMap.size() >0){
			StringBuilder errors = new StringBuilder();
			errors.append("计划删除的数据正在被以下数引用\n");
			for(EntityUsage entityUsage : entityUsageMap.values()){
				errors.append("\t").append(entityUsage.getEntityLabel()).append("\n");
				for(Map.Entry<Long,String> entry : entityUsage.getUsageIdNames().entrySet() ){
					errors.append("\t\t").append(entry.getKey()).append("\t").append(entry.getValue()).append("\n");
				}
			}
			errors.append("，不能删除，请检查处理后再删除");
			throw  new BusinessException(errors.toString());
		}

		Long rows = this.followStoreDao.deleteFollowStore(followStoreId);
		if(rows != 1){
			String error = "删除关注店铺出错，数据可能已经被删除";
			throw new BusinessException(error);
		}
	}

	//TODO:---------------验证-------------------

	private void validateFindFollowStores(PageDTO pageDTO) {
	//TODO:请使用下面方法添加数据过滤条件
	//		pageDTO.addFilter("creatorId",this.getLoginUserId());
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateFollowStore()写法
	}

	private void validateFindFollowStoresWithIdNameByName(String followStoreName) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateFollowStore()写法
	}


	private void validateFindAllFollowStoresWithIdName() {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateFollowStore()写法
	}

	private void validateFindFollowStoresWithIdNameById(Long followStoreId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateFollowStore()写法
	}

	private void validateFindFollowStore(Long followStoreId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateFollowStore()写法
	}

	private void validateFindFollowStoreWithForeignName(Long followStoreId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateFollowStore()写法
	}

	private void validateSaveFollowStore(FollowStore followStore) {
	//不为空判断
	if (followStore.getEid() != null || followStore.getCreatorId() != null || followStore.getCreateDatetime() != null) {
	throw new BusinessException("非法请求");
	}
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateFollowStore()写法
	}

	private void validateUpdateFollowStore(FollowStore followStore) {
	//不为空判断
	if (followStore.getEid() == null) {
	throw new BusinessException("唯一标识不能为空");
	}
	//是否存在判断
	if (this.followStoreDao.findFollowStoreTotalCount(PageDTO.create(FollowStore.FIELD_ID, followStore.getEid())) == 0) {
	throw new BusinessException("修改的关注店铺 " + followStore.getName() + " 不存在，修改失败，请重试或联系管理员");
	}
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateFollowStore()写法
	}

	private void validateDeleteFollowStore(Long followStoreId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateFollowStore()写法
	}

	@Override
	public boolean canDownloadAttachment(String formName, Long id) {
	return true;
	}
}
